#!/usr/bin/env python
#-*- coding:utf-8 -*-

import gtk, gtk.glade

from wordpath import *
from sound import play

class TestWord(gtk.VBox):
    """The word test widget for FirstRecite and WordRevise"""
    def __init__(self, wTree):
    #def __init__(self, rr, test_type, return_to, status, update_model, revise = None):

        self.wTree = wTree

        self.test_window = self.wTree.get_widget("window_testword")

        self.button_pronounce = self.wTree.get_widget("button_pronounce")
        self.button_pronounce.connect ("clicked", self.speak_button_clicked)

        self.entry_word = self.wTree.get_widget("entry_word")
        self.entry_word.connect("activate",self.check_error)
        self.entry_word.connect("insert-text", self.type_cb)
        self.entry_word.connect("backspace", self.backspace_cb)

        self.button_stop = self.wTree.get_widget("button_stop")
        self.button_stop.connect("clicked",self.exit_test_cb, True)
        
#         self.result = gtk.Label()

#         self.progress = gtk.Label()

#         self.test_type = test_type
#         self.return_to = return_to
#         self.status = status
#         self.update_model = update_model
#         self.save_revise = revise

#         self.create_test(rr)

#         self.review = WordReview(rr, self.exit_test_cb)
#         self.pack_start(self.review, False, False, 0)

    def speak_button_clicked(self, widget, data = None):
        read(self.now)

#     def create_test(self, rr = None):
#         """根据选中的背诵纪录，创建测试内容"""
#         self.rr = rr 
#         self.pause = False
#         self.correct = False
#         self.second = False
#         self.passed = []
#         self.failed = []

#         #如果是复习，则每次创建新的测试都清空队列，以防出错
#         if self.test_type == "revise":
#             self.keep = []
#             self.queue = []
#         if self.rr:
#             self.pool = copy.copy(self.rr.words)
#             self.now = self.next_word()
#             self.cn.set_text(self.rr.get_dict()[self.now])
#             self.progress.set_text("第1个(共%d)" % self.rr.num)

#     def next_word(self):
#         if self.correct:
#             now = random.sample(self.failed, 1)[0]
#         else:
#             now = random.sample(self.pool, 1)[0]
#             self.pool.remove(now)
#         return now

    def check_error(self, widget, data = None):
        if self.pause == True:
            if self.correct:
                #改错模式
                if len(self.failed) > 0:
                    self.progress.set_text("正在改正:剩余%d个" % len(self.failed))
                    self.now = self.next_word()
                    self.clear_last()
                else:
                    if self.test_type == "first":
                        if self.second:
                            self.finish_test()
                        else:
                            self.second = True
                            self.correct = False
                            self.passed = []
                            self.failed = []

                            self.pool = copy.copy(self.rr.words)
                            self.now = self.next_word()
                            self.clear_last()
                            show_info("加油！再复习一遍")
                            self.progress.set_text("第1个(共%d)" % self.rr.num)
                    else:
                        self.finish_test()
            else:
                sum = len(self.passed) + len(self.failed)
                if sum != self.rr.num:
                    self.progress.set_text("第%d个(共%d)" % (sum + 1, self.rr.num))
                if sum < len(self.rr.words):
                    self.now = self.next_word()
                    self.clear_last()
                else:
                    #判断做错的题目是否为0,如果不是就进行改错
                    if len(self.failed) == 0:
                        if self.test_type == "first":
                            if self.second:
                                self.finish_test()
                            else:
                                show_info("答完了！再复习一遍")
                                self.second = True
                                self.correct= False
                                self.passed = []
                                self.failed = []
                                self.pool = copy.copy(self.rr.words)

                                self.now = self.next_word()
                                self.clear_last()
                        else:
                            self.finish_test()
                    else:
                        self.correct = True
                        show_info("现在把答错的改正一下！")
                        self.progress.set_text("正在改正:剩余%d个" % len(self.failed))
                        self.now = self.failed[0]
                        self.clear_last()
        else:
            self.pause = True
            if self.now == self.entry.get_text():
                self.result.show()
                self.result.set_text("正确!按回车继续.")
                play("answerok")
                if self.now in self.failed:
                    self.failed.remove(self.now)
                self.passed.append(self.now)
            else:
                self.result.show()
                self.result.set_markup("错误!正确的应该是<b>%s</b>.按回车继续" % self.now)
                play("answerno")
                if not self.now in self.failed:
                    self.failed.append(self.now)

#     def clear_last(self):
#         self.cn.set_text(self.rr.get_dict()[self.now])
#         self.result.hide()
#         self.result.set_text("")
#         self.entry.set_text("")
#         self.pause = False

#     def save_record(self):
#         if self.test_type == "first":
#             f = file(os.path.join(os.path.expanduser("~"), ".wordjoy/record"), "ab")
#             pickle.dump(self.rr, f, True)
#             f.close()
#         else:
#             self.save_revise()

#     def finish_test(self):
#         self.save_record()
#         dialog = MessageDialog("测试完毕！\n还想做次词义回想以加深记忆吗？(可以不做)")
#         response = dialog.run()
#         if response == gtk.RESPONSE_YES:
#             self.status.set_markup('<span size="xx-large">词义回想</span>')
#             self.test_vbox.hide()
#             self.review.show()
#             self.review.start_review(self.rr)
#         else:    
#             self.exit_test_cb(None)
#         dialog.destroy()
        
    def exit_test_cb(self, widget, data = None):
        self.clear_last()
        self.return_to.show()
        if self.test_type == "first":
            self.update_model()
            self.status.set_markup('<span size="xx-large">单词初记-浏览</span>')
        else:
            self.update_model()
            self.status.set_markup('<span size="xx-large">单词复习-浏览</span>')
        self.test_vbox.show()
        self.review.hide()
        self.hide()

    def type_cb(self, widget, new_text, new_text_length, position, data = None):
        if not self.pause:
            play("type")

    def backspace_cb(self, widget, data = None):
        play("back")

if __name__ == "__main__":
    wTree = gtk.glade.XML(GLADE_PATH + "testword_test.glade")

    events_dic = {"on_window_testword_destroy":gtk.main_quit}
    wTree.signal_autoconnect(events_dic)

    TestWord(wTree)

    gtk.main()
